﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Windows.Forms;
using System.IO;

namespace autoBidProject
{
    class IBET
    {
        private static System.Windows.Forms.HtmlDocument htmldoc;

        private static void CheckRefreshSite()
        {
            System.Windows.Forms.HtmlDocument mainDocument = GetMainFrameHtmlDocument();
            if (mainDocument != null)
            {
                HtmlElement buttonFresh = null;
                if (Setting.bEventType)
                    buttonFresh = mainDocument.GetElementById("btnRefresh_L");
                else
                    buttonFresh = mainDocument.GetElementById("btnRefresh_D");

                if (buttonFresh != null)
                {
                    string innerText = buttonFresh.InnerText.Trim();
                    if (innerText != null)
                        if (innerText.CompareTo("Please wait") != 0)
                            buttonFresh.InvokeMember("click");
                }
            }
        }

        #region  Get event from IBET
        public static List<League> LoadFromIBET(System.Windows.Forms.HtmlDocument _htmldoc, bool bLiveEvent)
        {
            if (bLiveEvent)
                return GetLiveEventFromIBET(htmldoc);
            return GetNonLiveEventFromIBET(htmldoc);
        }

        private static List<League> GetLiveEventFromIBET(System.Windows.Forms.HtmlDocument htmldoc)
        {
            System.Windows.Forms.HtmlDocument mainDocument = GetMainFrameHtmlDocument();
            if (mainDocument != null)
            {
                HtmlElement livetable = mainDocument.GetElementById("oTableContainer_L"); //ibet: oTableContainer_L
                return GetEventFromIBET(livetable);
            }
            return null;
        }

        private static List<League> GetNonLiveEventFromIBET(System.Windows.Forms.HtmlDocument htmldoc)
        {
            System.Windows.Forms.HtmlDocument mainDocument = GetMainFrameHtmlDocument();
            if (mainDocument != null)
            {
                HtmlElement nonlivetable = mainDocument.GetElementById("oTableContainer_D");
                return GetEventFromIBET(nonlivetable);
            }
            return null;
        }

        private static List<League> GetEventFromIBET(HtmlElement table)
        {
            if (table == null)
                return null;
            List<League> leagues = null;
            if (table.InnerHtml != null)
            {
                HtmlAgilityPack.HtmlDocument agiDoc = new HtmlAgilityPack.HtmlDocument();
                string html = table.InnerHtml;//.Replace("<THead=\"\"", "");
                //html = html.Replace("</THead>", "");
                agiDoc.LoadHtml(html);

                File.WriteAllText("ibet_table_live.htm", html);
                File.WriteAllText("ibet_table_OuterHtml.htm", agiDoc.DocumentNode.OuterHtml);

                HtmlNodeCollection nodes = agiDoc.DocumentNode.SelectNodes("table/tbody/tr");  // "/thead=\"\"[1]/tbody[1]/tbody[1]/tr[12]"
                if (nodes != null)
                {
                    leagues = new List<League>();
                    League league = null;
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        String leagueName = "";
                        if (IsIbetLeague(nodes[i], ref leagueName))
                        {
                            if (league != null)
                                leagues.Add(league);

                            league = new League(leagueName);
                        }
                        else if (IsIbetEvent(nodes[i]))
                        {
                            Event e = LoadEvent(nodes[i]);
                            if(e != null)
                                league.Add(e);
                        }
                    }
                    if (league != null)
                        leagues.Add(league);
                }
            }
            return leagues;
        }

        private static Event LoadEvent(HtmlNode eventNode)
        {
            Event e = new Event();
            e.xpath = eventNode.XPath;

            HtmlNodeCollection elements = eventNode.SelectNodes("td[2]/div");
            if (elements != null)
            {
                e.name_home = elements[0].InnerText;
                e.name_away = elements[1].InnerText;
            }
            else
                return null;

            elements = eventNode.SelectNodes("td[4]");
            if (elements != null)
                e.ft_hdp = elements[0].InnerText.Trim();

            elements = eventNode.SelectNodes("td[10]");
            if (elements != null)
                e.fh_hdp = elements[0].InnerText.Replace("&nbsp;", "").Trim();

            e.ft_home = GetFloat(eventNode, "td[5]");
            e.ft_away = GetFloat(eventNode, "td[6]");
            e.ft_over = GetFloat(eventNode, "td[8]");
            e.ft_under = GetFloat(eventNode, "td[9]");

            e.fh_home = GetFloat(eventNode, "td[11]");
            e.fh_away = GetFloat(eventNode, "td[12]");
            e.fh_over = GetFloat(eventNode, "td[14]");
            e.fh_under = GetFloat(eventNode, "td[15]");
            return e;
        }

        private static float TryConvertFloat(string s)
        {
            try
            {
                return float.Parse(s);
            }
            catch (Exception)
            {
                return 0;
            }
        }

        private static bool IsIbetLeague(HtmlNode node, ref String leagueName)
        {
            HtmlNodeCollection league = node.SelectNodes("td[@class=\"tabtitle\"]");
            if (league != null)
                leagueName = league[0].InnerText.Trim();
            return league != null;
        }
        private static bool IsIbetEvent(HtmlNode node)
        {
            HtmlAttribute attrb = node.Attributes["class"];
            if (attrb != null)
                return (attrb.Value == "live") || (attrb.Value == "liveligh");
            return false;
        }
        #endregion

        private static float GetFloat(HtmlNode node, string xpath)
        {
            HtmlNodeCollection exist = node.SelectNodes(xpath);
            if (exist != null)
                try
                {
                    return float.Parse(exist[0].InnerText);
                }
                catch (Exception)
                {
                    return -1;
                }
            return -1;
        }

        private static System.Windows.Forms.HtmlDocument GetMainFrameHtmlDocument()
        {
            if (htmldoc != null)
            {
                HtmlWindow mainFrame = GetFrame(htmldoc, "mainFrame");
                if (mainFrame != null)
                    return mainFrame.Document;
            }
            return null;
        }

        private static HtmlWindow GetFrame(System.Windows.Forms.HtmlDocument htmldoc, string frameId)
        {
            if (htmldoc != null)
            {
                try
                {
                    if (htmldoc.Window.Frames.Count > 0)
                        return htmldoc.Window.Frames[frameId];
                }
                catch (Exception)
                {
                    return null;
                }
            }
            return null;
        }

        private HtmlElement GetElement(Event obetEvent, GlobalVar.ElementType type)
        {
            HtmlWindow mainFrame = GetFrame(htmldoc, "mainFrame");
            if (mainFrame != null)
            {
             //   mainFrame.Document.GetElementById();
            }

            return null;
        }

        internal static void Update(System.Windows.Forms.HtmlDocument htmlDocument)
        {
            htmldoc = htmlDocument;
            // disstyle 1 - 3
            CheckViewMode(htmlDocument);
            CheckRefreshSite();
        }

        private static void CheckViewMode(System.Windows.Forms.HtmlDocument htmlDocument)
        {
            HtmlWindow mainFrame = GetFrame(htmlDocument, "mainFrame");
            if (mainFrame != null)
            {
                System.Windows.Forms.HtmlDocument frameDoc = mainFrame.Document;
                HtmlElement disstyle = frameDoc.GetElementById("disstyle");
                if (disstyle != null)
                {
                    string select = disstyle.GetAttribute("selectedIndex");
                    if (select != "0")
                    {
                        disstyle.SetAttribute("selectedIndex", "0");
                        disstyle.InvokeMember("onchange");
                    }
                    else
                        disstyle.SetAttribute("disabled", "true");
                    //oddsMode.Enabled = false;   // cái này cũng được
                }
            }
        }
    }
}
